package com.rzjm.exercise.module.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 企业
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2020-12-15 22:36:23
 */
@Controller
@RequestMapping("/module/feedQr")
public class ShopQrCodeController extends BaseController {
    @Resource
    private ShopService shopService;
    @Resource
    private DeviceRangeQrCodeService deviceRangeQrCodeService;
    @Resource
    private DeviceRangeFeedRecordService deviceRangeFeedRecordService;

    @Value("${projecturl.uploadPath}")
    private String uploadPath;
    @Value("${projecturl.imgurl}")
    private String imgurl;


    @Log("查询设备页面")
    @GetMapping("")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String shopList1(Model model) {
        model.addAttribute("shopType",5);
//        model.addAttribute("deviceType",deviceType);//   0 - 测量仓  1 - 测油罐
        return "module/shop/qrcode/shop";
    }

    @Log("查询设备页面")
    @GetMapping("/qrCode/{shopId}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String qrCodeList(Model model,@PathVariable("shopId") Integer shopId) {
        model.addAttribute("shopId",shopId);
//        model.addAttribute("deviceType",deviceType);//   0 - 测量仓  1 - 测油罐
        return "module/shop/qrcode/qrcode";
    }

    @Log("查询设备页面")
    @GetMapping("/qrCode/feedRecord/{qrCodeId}")
    @RequiresPermissions("module:deviceRange:deviceRange")
    String qrCodeRecordList(Model model,@PathVariable("qrCodeId") Integer qrCodeId) {
        model.addAttribute("qrCodeId",qrCodeId);

        model.addAttribute("begin_date",DateUtils.getDay());
        model.addAttribute("end_date",DateUtils.getDay());

        return "module/shop/qrcode/feedRecord";
    }



    @Log("查询设备")
    @ResponseBody
    @GetMapping("/qrCode/list")
    @RequiresPermissions("module:feedQr:feedQr")
    public DataTableLayUI<DeviceRangeQrCode> qrCodeList(DataTableLayUI<DeviceRangeQrCode> condition) {
        DataTableLayUI<DeviceRangeQrCode> dt = deviceRangeQrCodeService.pageSearchLayUI(condition);
        List<DeviceRangeQrCode> devices = dt.getData();
        if(CollUtil.isNotEmpty(devices)){
            for (DeviceRangeQrCode qrCode: devices){
                qrCode.setQrCodeUrl( imgurl + qrCode.getQrCodeUrl());
            }
        }
        return dt;
    }


    @Log("查询设备")
    @ResponseBody
    @GetMapping("/qrCode/feedRecord/list")
    @RequiresPermissions("module:feedQr:feedQr")
    public DataTableLayUI<DeviceRangeFeedRecord> qrCodeFeedRecordList(DataTableLayUI<DeviceRangeFeedRecord> condition) {

        QueryWrapper<DeviceRangeFeedRecord> qw = new QueryWrapper<>();
        Map<String,Object> map = condition.getSearchParams();

        String qrCodeId = map.containsKey("search_eq_qrCodeId")?map.get("search_eq_qrCodeId").toString():null;
        String begin_date = map.containsKey("begin_date") ? map.get("begin_date").toString(): null;
        String end_date = map.containsKey("end_date") ? map.get("end_date").toString(): null;

        if(StrUtil.isNotEmpty(qrCodeId)){
            qw.eq("qr_code_id",qrCodeId);
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time",begin_date,end_date);
        }

        condition.setQw(qw);
        DataTableLayUI<DeviceRangeFeedRecord> dt = deviceRangeFeedRecordService.pageSearchLayUI(condition);
        List<DeviceRangeFeedRecord> records = dt.getData();
        return dt;
    }


    @GetMapping("/exportExcel")
    public void testExportExcel(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("qrCodeId") String qrCodeId, HttpServletResponse response){
//        UserDO user = getUser();
//        Map<String,Object> map = new HashMap<>();
//        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
//            map.put("begin_time",begin_date +" 00:00:00");
//            map.put("end_time", end_date +" 23:59:59");
//        }else{
//
//        }
        String qrName = "";
        DeviceRangeQrCode rangeQrCode = deviceRangeQrCodeService.findById(qrCodeId);
        if(rangeQrCode!= null){
            qrName = rangeQrCode.getQrName();
        }
        QueryWrapper<DeviceRangeFeedRecord> qw = new QueryWrapper<>();
        qw.eq("qr_code_id",qrCodeId);
        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
        }else{
            begin_date = DateUtils.getMonthStr(new Date()) + "-01";
            end_date = DateUtils.getDay();
            qw.between("create_time",begin_date +" 00:00:00",end_date +" 23:59:59");
        }
        qw.orderByAsc("create_time");
        List<DeviceRangeFeedRecord> records = deviceRangeFeedRecordService.list(qw);

        records.forEach(record->{
            record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));
//            record.setWeightDun(record.getWeight() + "吨");
            if(record.getInOrOut() == 0){
                record.setInOrOutStr("出料");
            }else{
                record.setInOrOutStr("进料");
            }
        });

        ExcelUtils.writeExcel(response, records, DeviceRangeFeedRecord.class, qrName + "_" + System.currentTimeMillis() + "_进出仓结果.xlsx");
    }




    @Log("新增设备页面")
    @GetMapping("/addQrCode/{shopId}")
    @RequiresPermissions("module:feedQr:add")
    String addQrCode(Model model,@PathVariable("shopId") Integer shopId) {
        DeviceRangeQrCode qrCode = new DeviceRangeQrCode();
        qrCode.setShopId(shopId);
        Shop shop = shopService.findById(shopId);
        if(shop != null){
            qrCode.setShopName(shop.getShopName());
        }

        qrCode.setState(1);
        model.addAttribute("qrCode", qrCode);
        return "module/shop/qrcode/detail";
    }


    @Log("编辑设备页面")
    @GetMapping("/editQrCode/{id}")
    @RequiresPermissions("module:feedQr:edit")
    String editQrCode(@PathVariable("id") Integer id, Model model) {
        DeviceRangeQrCode qrCode = deviceRangeQrCodeService.findById(id);
        model.addAttribute("qrCode", qrCode);
        return "module/shop/qrcode/detail";
    }


    /**
     * 保存
     */
    @Log("新增设备")
    @ResponseBody
    @PostMapping("/saveQrCode")
    @RequiresPermissions("module:feedQr:add")
    public R saveQrCode(@Valid DeviceRangeQrCode rangeQrCode) {

        boolean bl = deviceRangeQrCodeService.save(rangeQrCode);

        if (bl) {
            try{
                String qrCode = "";
                String fileName = rangeQrCode.getQrName() + "_" + rangeQrCode.getId() +".jpg";
                String content = "{\"qrtype\":\"range\",\"shop_id\":" + rangeQrCode.getShopId() + ",\"qr_id\":" + rangeQrCode.getId()+"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_DEVICE_RANGE_PHOTOS) + rangeQrCode.getShopId() + "/"  + fileName;
                QRCodeUtilEx.createQrCodeImg(content, rangeQrCode.getQrName(), null,
                        uploadPath +"/"+ img_key, true);
                qrCode = img_key;
                rangeQrCode.setQrCodeUrl(qrCode);
                bl = deviceRangeQrCodeService.updateById(rangeQrCode);
            }catch (Exception e){
                e.printStackTrace();
            }
            return R.ok();
        }
        return R.error();
    }

    /**
     * 更新二维码
     */
    @Log("更新二维码")
    @ResponseBody
    @RequestMapping("/updateQrCode")
    @RequiresPermissions("module:feedQr:edit")
    public R updateQrCode(@Valid DeviceRangeQrCode qrCode) {
        boolean bl = deviceRangeQrCodeService.updateById(qrCode);
        if(bl){
            return R.ok();
        }
        return R.error();
    }


    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @ResponseBody
    @RequestMapping("/resetQrCode")
    @RequiresPermissions("module:feedQr:edit")
    public R resetQrCode(@Valid DeviceRangeQrCode rangeQrCode) {

        rangeQrCode = deviceRangeQrCodeService.findById(rangeQrCode.getId());
        try{
            String qrCode = "";
            String fileName = rangeQrCode.getQrName() + "_" + rangeQrCode.getId() +".jpg";
            String content = "{\"qrtype\":\"range\",\"shop_id\":" + rangeQrCode.getShopId() + ",\"qr_id\":" + rangeQrCode.getId()+"}";
            Aes aes = new Aes();
            content = aes.encrypt(content);
            System.out.println("content:  "+ content);
            //上传头像到OSS
            String img_key = OssUtil.getUploadPrefix(OssUtil.TYPE_DEVICE_RANGE_PHOTOS) + rangeQrCode.getShopId() + "/"  + fileName;
            QRCodeUtilEx.createQrCodeImg(content, rangeQrCode.getQrName(), null,
                    uploadPath +"/"+ img_key, true);
            qrCode = img_key;
            rangeQrCode.setQrCodeUrl(qrCode);
        }catch (Exception e){
            e.printStackTrace();
        }

        boolean bl = deviceRangeQrCodeService.updateById(rangeQrCode);
        if(bl){
            return R.ok();
        }
        return R.error();
    }



    /**
     * 下载二维码
     */
    @Log("下载二维码")
    @GetMapping("/downloadQrCode/{qrCodeId}")
    public void download(@PathVariable("qrCodeId") Integer qrCodeId, HttpServletResponse response) {
        DeviceRangeQrCode qrCode = deviceRangeQrCodeService.findById(qrCodeId);
        if(qrCode!=null){
            FileUtils.download(uploadPath + qrCode.getQrCodeUrl(),response);
        }
    }
    /**
     * 删除
     */
    @Log("删除二维码")
    @PostMapping( "/removeQrCode")
    @ResponseBody
    @RequiresPermissions("module:feedQr:remove")
    public R removeQrCode( Integer id) {
        if (deviceRangeQrCodeService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @Log("删除二维码")
    @PostMapping( "/removeFeedRecord")
    @ResponseBody
    @RequiresPermissions("module:feedRecord:remove")
    public R removeFeedRecord( Integer id) {
        if (deviceRangeFeedRecordService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }
}
